var app = getApp();
Page({
  data: {
    reward: '',
    deposit: '',
    brokerage: 0,
    remark: '',
    total: 0,
    items: [
      { id: 'tel', value: '', icon: 'icon-phone', alert: '请输入手机号', checked: false },
      { id: 'wx', value: '', icon: 'icon-weixin', alert: '请输入微信号', checked: false }
    ],
    uploadImgList: [],
    pictures: [],
    attache: '',
    removed: '',
    contact: ''
  },
  onLoad: function(options) {
    var that = this;
    that.setData({
      trip_id: options.tripId,
      surplus_money: options.surplus_money,
      reward_min: options.reward_min,
      items: [
        { id: 'tel', value: wx.getStorageSync("mobile"), icon: 'icon-phone', alert: '请输入手机号', checked: false },
        { id: 'wx', value: wx.getStorageSync("wxid"), icon: 'icon-weixin', alert: '请输入微信号', checked: false }
      ]
    })
    //that.resetData();
  },
  onShow: function() {
    var that = this;
    //that.resetData();
    app.getLocation(function (data) {
      that.setData({
        lng: data.lng,
        lat: data.lat,
        province: data.province,
        city: data.city
      })
    })
  },
  contactSelect: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.data.items[index].checked = !that.data.items[index].checked;
    that.setData({
      items: that.data.items
    })
  },
  contactWay: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.data.items[index].value = e.detail.value;
    that.setData({
      items: that.data.items
    })
  },
  sxfTip: function(e) {
    wx.showModal({
      title: '提示',
      content: '第三方支付将收取本平台千分之六的收费，另外千分之四作为平台服务费，下单后手续费无法退还。',
      showCancel: false,
      success: function(res) {}
    })
  },
  remarkTap: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  rewardTap: function (e) {
    var value = e.detail.value;
    var that = this;
    if (value > 5000) {
      value = 5000;
    }
    that.setData({
      reward: value,
      brokerage: (parseFloat(value == '' ? 0 : value) + parseFloat(that.data.deposit == '' ? 0 : that.data.deposit)) * 0.01,
      total: (parseFloat(value == '' ? 0 : value) + parseFloat(that.data.deposit == '' ? 0 : that.data.deposit)) * 1.01
    })
  },
  depositTap: function (e) {
    var value = e.detail.value;
    var that = this;
    if (value > parseFloat(that.data.surplus_money)) {
      value = parseFloat(that.data.surplus_money);
    }
    that.setData({
      deposit: value,
      brokerage: (parseFloat(value == '' ? 0 : value) + parseFloat(that.data.reward == '' ? 0 : that.data.reward)) * 0.01,
      total: (parseFloat(value == '' ? 0 : value) + parseFloat(that.data.reward == '' ? 0 : that.data.reward)) * 1.01
    })
  },
  resetData: function() {
    var that = this;
    that.setData({
      remark: '',
      reward: '',
      deposit: '',
      brokerage: 0,
      total: 0,
      items: [
        { id: 'tel', value: wx.getStorageSync("mobile"), icon: 'icon-phone', alert: '请输入手机号', checked: false },
        { id: 'wx', value: wx.getStorageSync("wxid"), icon: 'icon-weixin', alert: '请输入微信号', checked: false }
      ],
      uploadImgList: [],
      pictures: [],
      attache: '',
      removed: '',
      contact: ''
    })
  },
  sendtap: function(e) {
    var that = this;

    //判断是否实名认证
    if (wx.getStorageSync("certification") == 'false') {
      wx.showModal({
        title: '提示',
        content: '实名认证用户才能发布!',
        showCancel: false,
        success: function(res) {
          wx.navigateTo({
            url: '../my/pages/certification/certification',
          })
        }
      });
      return false;
    }

    //判断是否输入需求描述
    if (that.data.remark == '' || that.data.remark.length < 40) {
      wx.showModal({
        title: '提示',
        content: '请输入不少于40字的需求描述!',
        showCancel: false,
        success: function (res) { }
      });
      return false;
    }

    //判断是否输入赏金
    if (that.data.reward == '') {
      wx.showModal({
        title: '提示',
        content: '请输入赏金!',
        showCancel: false,
        success: function(res) {}
      });
      return false;
    } else if (parseFloat(that.data.reward) < parseFloat(that.data.reward_min)) {
      wx.showModal({
        title: '提示',
        content: '您输入的赏金不能低于最低赏金￥' + that.data.reward_min +'!',
        showCancel: false,
        success: function (res) { }
      });
      return false;
    }

    //判断是否输入预付款
    // if (that.data.deposit == '') {
    //   wx.showModal({
    //     title: '提示',
    //     content: '请输入预付款!',
    //     showCancel: false,
    //     success: function(res) {}
    //   });
    //   return false;
    // }

    //获取联系方式
    var items = that.data.items;
    var contact = '';
    for (var i in items) {
      if (items[i].checked == true) {
        if (items[i].value == '') {
          wx.showModal({
            title: '提示',
            content: items[i].alert,
            showCancel: false,
            success: function (res) { }
          });
          return false;
        } else {
          contact += items[i].id + ":" + items[i].value + "|";
        }
      }
    }
    that.setData({
      contact: contact.substring(0, contact.length - 1)
    });

    //判断是否输入联系方式
    if (that.data.contact == '') {
      wx.showModal({
        title: '提示',
        content: '联系方式不能为空!',
        showCancel: false,
        success: function (res) { }
      });
      return false;
    }

    //判断金额
    if (parseFloat(that.data.total) > 0) {
      wx.showModal({
        title: '提示',
        content: '点击“确定”支付该订单',
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            var attache = that.data.attache;
            var removed = that.data.removed;
            var jsonPayData = {
              trip_id: that.data.trip_id,
              reward: that.data.reward,
              deposit: that.data.deposit == '' ? 0 : that.data.deposit,
              brokerage: that.data.brokerage,
              remark: that.data.remark,
              type: 1,
              attache: attache != '' ? attache.substring(0, attache.length - 1) : '',
              removed: removed != '' ? removed.substring(0, removed.length - 1) : '',
              contact: that.data.contact,
              lng: that.data.lng,
              lat: that.data.lat,
              province: that.data.province,
              city: that.data.city
            };
            app.showLoading("正在提交...请稍后...");
            app.JsonPost("Api/Pay/index", jsonPayData, function (data) {
              app.closeLoading();
              if (data !== false) {
                wx.requestPayment({
                  timeStamp: data.timeStamp + "",
                  nonceStr: data.nonceStr,
                  package: data.package,
                  signType: data.signType,
                  paySign: data.paySign,
                  success(res) {
                    wx.showModal({
                      title: '提示',
                      content: '下单成功!',
                      showCancel: false,
                      success: function (res) {
                        that.resetData();
                        wx.switchTab({
                          url: 'order'
                        });
                      }
                    });
                  },
                  fail(res) {
                    wx.showModal({
                      title: '提示',
                      content: '下单失败!',
                      showCancel: false,
                      success: function (res) {
                        that.resetData();
                      }
                    });
                  }
                })
              }
            })
          }
        }
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '订单金额不能为0!',
        showCancel: false,
        success: function (res) {}
      });
    }
  },
  uploadpic: function(e) {
    var that = this;
    // var old_data = {
    //   reward: that.data.reward,
    //   deposit: that.data.deposit,
    //   brokerage: that.data.brokerage,
    //   remark: that.data.remark,
    //   total: that.data.total,
    //   items: that.data.items,
    //   contact: that.data.contact
    // };
    var uploadImgList = that.data.uploadImgList;
    if (uploadImgList.length < 6) {
      wx.chooseImage({
        count: 6 - uploadImgList.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          var tempFiles = res.tempFiles;

          var pictures = that.data.pictures;
          //循环把图片加入上传列表
          for (var i in tempFiles) {
            tempFiles[i]['upload_percent'] = 0;
            tempFiles[i]['path_server'] = '';
            uploadImgList.push(tempFiles[i]);
            pictures[i] = uploadImgList[i].path;
          }
          that.setData({
            uploadImgList: uploadImgList,
            pictures: that.data.pictures
          })
          console.log(that.data.pictures)
          //循环把图片上传到服务器 并显示进度
          for (var j in uploadImgList) {
            if (uploadImgList[j]['upload_percent'] == 0) {
              upload_file_server(that, uploadImgList, j)
            }
          }
        },
        // complete: function () {
        //   that.setData(old_data);
        // }
      })
    } else {
      wx.showToast({
        title: '上传图片不能大于6张!',
        icon: 'none'
      })
    }
  },
  deleteImg: function(e) {
    var that = this;
    var uploadImgList = that.data.uploadImgList;
    var pictures = that.data.pictures;
    var index = e.currentTarget.dataset.index;
    var imgid = uploadImgList[index].attachement_id;
    //console.log(imgid);
    uploadImgList.splice(index, 1);
    pictures.splice(index, 1);
    console.log(pictures);
    that.setData({
      uploadImgList: uploadImgList,
      attache: that.data.attache.replace(imgid, ""),
      removed: that.data.removed + imgid,
      pictures: pictures
    });
  },
  previewImg: function (e) {
    var that = this;
    var current = e.target.dataset.src;
    var pictures = that.data.pictures;
    wx.previewImage({
      current: current,
      urls: pictures
    })
  }
})

function upload_file_server(that, uploadImgList, j) {
  var upload_task = wx.uploadFile({
    url: 'https://www.saixingchi.com/Api/Upload/index',
    filePath: uploadImgList[j]['path'],
    name: 'file',
    formData: {
      user_id: wx.getStorageSync("userId"),
      type: 'order',
      ajax: 1
    },
    success: function(res) {
      var data = JSON.parse(res.data);
      var imgid = '';
      if (data.msg == "success") {
        //var filename = "https://www.saixingchi.com/" + data.data[0].filePath;
        imgid = data.data[0].attachement_id + ',';
        //uploadImgList[j]['path_server'] = filename;
        uploadImgList[j]['attachement_id'] = imgid;
      }
      that.setData({
        uploadImgList: uploadImgList,
        attache: that.data.attache + imgid
      })
    }
  })
  upload_task.onProgressUpdate((res) => {
    uploadImgList[j]['upload_percent'] = res.progress;
    that.setData({
      uploadImgList: uploadImgList
    })
  })
}